<?php
class ControllerModuleNewsletter extends Controller {
	public function index() {	
		$this->language->load('module/newsletter');
    	
		//$this->document->title = $this->language->get('heading_title');
		$this->data['template'] = $this->config->get('config_template');  
				
    	$this->data['heading_title'] = $this->language->get('heading_title');  
    	$this->data['text_success'] = $this->language->get('text_success'); 		
		$this->data['button_continue'] = $this->language->get('button_continue');
		$this->data['button_back'] = $this->language->get('button_back');

    	$this->data['action'] = HTTPS_SERVER . 'index.php?route=module/newsletter';		
		$this->data['continue'] = HTTPS_SERVER . 'index.php?route=common/home';
		$this->data['unsubscriber_url'] = HTTPS_SERVER . 'index.php?route=module/newsletter/unsubscriberMail'; 
		$this->data['subscriber_url'] = HTTPS_SERVER . 'index.php?route=module/newsletter/subscriberMail';
		$this->data['subscriber_cc_url'] = HTTPS_SERVER . 'index.php?route=module/newsletter/subscriberCC';
		
		$this->load->model('tool/seo_url');
		$this->data['newsletter_url'] = $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=newsletter/newsletter'); 
		
		$this->load->model('setting/tooltip'); 
		$this->data['newsletter_text'] = $this->model_setting_tooltip->getNewsletterText();
				
		$this->id = 'newsletter';
		
		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/newsletter.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/module/newsletter.tpl';
		} else {
			$this->template = 'default/template/module/newsletter1.tpl';
		}
		
		$this->render();	
  	}
	
	public function indexOld() {	
		$this->language->load('module/newsletter');
    	
		//$this->document->title = $this->language->get('heading_title');
		$this->data['template'] = $this->config->get('config_template');  
				
    	$this->data['heading_title'] = $this->language->get('heading_title');  
    	$this->data['text_success'] = $this->language->get('text_success'); 		
		$this->data['button_continue'] = $this->language->get('button_continue');
		$this->data['button_back'] = $this->language->get('button_back');

    	$this->data['action'] = HTTPS_SERVER . 'index.php?route=module/newsletter';		
		$this->data['continue'] = HTTPS_SERVER . 'index.php?route=common/home';
		$this->data['unsubscriber_url'] = HTTPS_SERVER . 'index.php?route=module/newsletter/unsubscriberMail'; 
		$this->data['subscriber_url'] = HTTPS_SERVER . 'index.php?route=module/newsletter/subscriberMail'; 
		
		$this->id = 'newsletter';
		
		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/newsletter.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/module/newsletter.tpl';
		} else {
			$this->template = 'default/template/module/newsletter.tpl';
		}
		
		$this->render();	
  	}
  	
  	private function validate() {
  		//$pattern = '/^[A-Z0-9._%-+]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z]{2,6}$/i';
		$pattern = "/^([a-zA-Z0-9])+([a-zA-Z0-9+\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/";
		$error = false;
    	if (!preg_match($pattern, $this->request->post['email'])) {
      		//$this->error['email'] = $this->language->get('error_email');
      		$error = true;
    	}

    	//if (!$this->error) {     
    	if (!$error) {     
      		return true;     
    	} 
    	else {
      		return false;
    	}
  	}
  	
  	public function subscriberMail() {	
		$this->language->load('module/newsletter');
		$result = $this->language->get('text_success');
		
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			$this->load->model('account/customer');
			
			if($this->model_account_customer->checkNewsletter($this->request->post['email'])){
				$result = $this->language->get('text_duplicate');
			}
			else{
				$data = array(
					'email'	=> $this->request->post['email'],
					'name'	=> $this->request->post['name']
				);				
				$this->model_account_customer->addNewsletter($data);                 
				
				//$this->subscriberCC($data);
				$result = $this->language->get('text_success');
				
                /*
				$subject = 'Abonnent Nyhedsbrev';
				$message = 'Kære!<br />Din e-mail har været en succes tilføjet til vores abonnent system.<br /><br />';
				$message .= '<b><a href="' . $this->config->get('config_url') . '">' . $this->config->get('config_name') . '</a></b><br />';
				$message .= str_replace("\n", '<br />', $this->config->get('config_address')) . '<br />';
				$message .= 'Tel: ' . $this->config->get('config_telephone') . '<br />';
				$message .= 'Fax: '  . $this->config->get('config_fax') . '<br />';
				$message .= 'Email: ' . $this->config->get('config_email');
				
				$this->sendMail($this->request->post['email'], $subject, $message);
                */
			}
		}
		else{
			$result = $this->language->get('error_email');
		}
		
		echo $result;			
  	}
  	
  	public function unsubscriberMail() {	
		$this->language->load('module/newsletter');
		$result = $this->language->get('text_remove_success');
		
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			$this->load->model('account/customer');
			
			if(!$this->model_account_customer->checkNewsletter($this->request->post['email'])){
				$result = $this->language->get('text_no_email');
			}
			else{				
				$this->model_account_customer->removeNewsletter($this->request->post['email']);
				
                /*
				$subject = 'Afmelde Nyhedsbrevet';
				$message = 'Kære!<br />Din e-mail er blevet en succes fjernet fra vores abonnent system.<br /><br />';
				$message .= '<b><a href="' . $this->config->get('config_url') . '">' . $this->config->get('config_name') . '</a></b><br />';
				$message .= str_replace("\n", '<br />', $this->config->get('config_address')) . '<br />';
				$message .= 'Tel: ' . $this->config->get('config_telephone') . '<br />';
				$message .= 'Fax: '  . $this->config->get('config_fax') . '<br />';
				$message .= 'Email: ' . $this->config->get('config_email');
				
				$this->sendMail($this->request->post['email'], $subject, $message);
                */
			}
		}
		else{
			$result = $this->language->get('error_email');
		}
		
		echo $result;			
  	}
  	
  	private function sendMail($email, $subject, $message){
		$mail = new Mail();
		$mail->protocol = $this->config->get('config_mail_protocol');
		$mail->parameter = $this->config->get('config_mail_parameter');
		$mail->hostname = $this->config->get('config_smtp_host');
		$mail->username = $this->config->get('config_smtp_username');
		$mail->password = $this->config->get('config_smtp_password');
		$mail->port = $this->config->get('config_smtp_port');
		$mail->timeout = $this->config->get('config_smtp_timeout');				
		$mail->setTo($email);
	  	$mail->setFrom($this->config->get('config_email'));
	  	$mail->setSender($this->config->get('config_name'));
	  	$mail->setSubject($subject);
	  	//$mail->setText(strip_tags(html_entity_decode($message, ENT_QUOTES, 'UTF-8')));
	  	$mail->setHtml($message); 
      	$mail->send();	
  	}

	public function subscriberCC($data) {	
		// Use API to add data to ConstantContact newsletter system
		require_once(str_replace('catalog', 'newsletter/constantcontact', DIR_APPLICATION) . 'cc_class.php');
		$ccContact = new CC_Contact();
		$ccList = new CC_List(); 
		// Get all available lists for the current CC account.
		$allLists = $ccList->getLists(); 
		// Fill all for the contact.
		$postFields = array();
		$name = explode(' ', $data["name"]);
		$postFields["email_address"] = $data["email"];
		$postFields["first_name"] = trim($name[0]);
		unset($name[0]);
		$postFields["last_name"] = trim(implode(' ', $name));
		$postFields["middle_name"] = '';
		$postFields["home_number"] = '';
		$postFields["address_line_1"] = '';
		$postFields["address_line_2"] = '';
		$postFields["address_line_3"] = '';
		$postFields["city_name"] = '';
		$postFields["state_code"] = '';				
		$postFields["state_name"] = '';
		$postFields["country_code"] = '';
		$postFields["zip_code"] = '';
		$postFields["sub_zip_code"] = '';
		$postFields["mail_type"] = 'HTML';
		
		$group = array();
		foreach ($allLists as $k => $item) {
			$group[] = $item['id'];
		}
		$postFields["lists"] = $group;
		
		try{
			$contactXML = $ccContact->createContactXML(null, $postFields);
			$error = !$ccContact->addSubscriber($contactXML);					
		} 
		catch (Exception $e) {
			$error = "<span style='color:red;'>" . $e . "</span>";
		}
	}
}
?>